package com.ty.springbootredis.unit;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * RedisPool
 *
 * @aurhor Administrator  whs
 * @since 2024/9/25
 */
public final class RedisPool {

    // Redis 服务器 IP
    private static String ADDR = "192.168.0.1";
    // Redis 的端口号
    private static int PORT = 6379;
    // 访问密码
    private static String AUTH = "whs";

    private static int MAX_ACTIVE = 1024;

    private static int MAX_IDLE = 200;

    private static int MAX_WAIT = 10000;

    private static int TIMEOUT = 10000;

    private static JedisPool jedisPool = null;

    private static boolean Test_ON_Borrow = true;


    /**
     * 初始化 Redis 连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(MAX_IDLE);
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(Test_ON_Borrow);
            jedisPool = new JedisPool(config,ADDR,PORT,TIMEOUT,AUTH);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取 Jedis 实例
     */
    public synchronized static Jedis getJedis(){
        try {
            if (jedisPool != null){
                return jedisPool.getResource();
            }else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 释放 jedis资源
     */
    public static void returnJedis(final Jedis jedis){
        if (jedis != null){
            jedisPool.returnResource(jedis);
        }
    }


}
